// 全局变量
let orderId = null;
let orderInfo = null;
let selectedPaymentMethod = 'ALIPAY';
let countdownTimer = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function () {

    // 初始化页面
    initPage();

    // 绑定事件
    bindEvents();
});

// 初始化页面
function initPage() {
    // 检查用户是否登录
    const token = localStorage.getItem('token');
    if (!token) {
        // 未登录，跳转到登录页
        window.location.href = './login.html?redirect=' + encodeURIComponent(window.location.href);
        return;
    }

    // 获取订单ID
    const urlParams = new URLSearchParams(window.location.search);
    orderId = urlParams.get('orderId');

    if (!orderId) {
        // 没有订单ID，返回订单列表页
        layui.use('layer', function () {
            const layer = layui.layer;
            layer.msg('订单信息不存在', { icon: 0 });
            setTimeout(() => {
                window.location.href = './order.html';
            }, 1500);
        });
        return;
    }

    // 加载订单信息
    loadOrderInfo(orderId);
}

// 加载订单信息
function loadOrderInfo(orderId) {
    layui.use('layer', function () {
        const layer = layui.layer;
        const loadingIndex = layer.load(2);

        ApiService.order.getOrderDetail(orderId)
            .then(response => {
                layer.close(loadingIndex);

                if (response.data) {
                    orderInfo = response.data;

                    const order = response.data;

                    // 更新订单基本信息
                    document.getElementById('orderNumber').textContent = order.orderNumber || order.id;
                    document.getElementById('orderAmount').textContent = `¥${order.totalAmount.toFixed(2)}`;
                    document.getElementById('orderStatus').textContent = getOrderStatusText(order.status);

                    // 渲染订单商品
                    renderOrderItems(order.items);

                    // 启动倒计时 - 使用订单的过期时间，如果没有则设置为当前时间后1小时
                    let expireTime;
                    if (order.expireTime) {
                        expireTime = order.expireTime;
                    } else {
                        const date = new Date();
                        date.setHours(date.getHours() + 1);
                        expireTime = date.toISOString();
                    }
                    
                    // 只调用一次倒计时函数
                    startCountdown(expireTime);
                } else {
                    layer.msg('订单信息不存在', { icon: 0 });
                    setTimeout(() => {
                        window.location.href = './order.html';
                    }, 1500);
                }
            })
            .catch(error => {
                layer.close(loadingIndex);
                console.error("获取订单信息失败:", error);
                layer.msg('获取订单信息失败，请重试', { icon: 2 });
            });
    });
}

// 启动倒计时
function startCountdown(expireTimeString) {
    console.log("倒计时开始，过期时间:", expireTimeString);
    
    // 确保过期时间是有效的日期
    let expireTime;
    try {
        expireTime = new Date(expireTimeString);
        // 检查是否是有效日期
        if (isNaN(expireTime.getTime())) {
            console.error("无效的过期时间格式:", expireTimeString);
            // 默认设置为当前时间后1小时
            expireTime = new Date();
            expireTime.setHours(expireTime.getHours() + 1);
        }
    } catch (error) {
        console.error("解析过期时间出错:", error);
        // 默认设置为当前时间后1小时
        expireTime = new Date();
        expireTime.setHours(expireTime.getHours() + 1);
    }
    
    const countdownElement = document.getElementById('countdown');

    // 清除现有的倒计时
    if (countdownTimer) {
        clearInterval(countdownTimer);
    }

    // 更新倒计时
    function updateCountdown() {
        const now = new Date();
        let remainingTime = expireTime - now;

        if (remainingTime <= 0) {
            clearInterval(countdownTimer);
            countdownElement.textContent = '已过期';

            // 订单已过期，返回订单列表
            layui.use('layer', function () {
                const layer = layui.layer;
                layer.msg('订单已过期', { icon: 0 });
                setTimeout(() => {
                    window.location.href = './order.html';
                }, 1500);
            });
            return;
        }

        // 转换为时分秒
        const hours = Math.floor(remainingTime / (1000 * 60 * 60));
        remainingTime %= (1000 * 60 * 60);

        const minutes = Math.floor(remainingTime / (1000 * 60));
        remainingTime %= (1000 * 60);

        const seconds = Math.floor(remainingTime / 1000);

        countdownElement.textContent = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
    }

    // 立即更新一次
    updateCountdown();

    // 每秒更新一次
    countdownTimer = setInterval(updateCountdown, 1000);
}

// 绑定事件
function bindEvents() {
    // 支付方式选择
    document.querySelectorAll('.payment-option').forEach(option => {
        option.addEventListener('click', function () {
            document.querySelectorAll('.payment-option').forEach(o => o.classList.remove('active'));
            this.classList.add('active');
            selectedPaymentMethod = this.getAttribute('data-method');

            // 更新支付方式文本
            const methodTextMap = {
                'ALIPAY': '支付宝',
                'WECHAT': '微信',
                'BANK': '银行卡'
            };
            document.getElementById('paymentMethodText').textContent = methodTextMap[selectedPaymentMethod] || '支付宝';
        });
    });

    // 支付按钮
    const payBtn = document.querySelector('.pay-btn');
    if (payBtn) {
        payBtn.addEventListener('click', startPayment);
    }

    // 取消支付按钮
    const cancelBtn = document.querySelector('.cancel-btn');
    if (cancelBtn) {
        cancelBtn.addEventListener('click', cancelPayment);
    }
}

// 开始支付
function startPayment() {
    if (!orderInfo) {
        layui.use('layer', function () {
            const layer = layui.layer;
            layer.msg('订单信息不存在', { icon: 0 });
        });
        return;
    }

    layui.use('layer', function () {
        const layer = layui.layer;
        const loadingIndex = layer.load(2);

        // 调用支付接口
        ApiService.order.payOrder(orderId, selectedPaymentMethod)
            .then(response => {
                layer.close(loadingIndex);

                if (response.data) {
                    // // 显示支付二维码
                    // document.querySelector('.payment-qrcode').style.display = 'block';

                    // // 设置二维码图片
                    // const qrcodeImg = document.getElementById('qrcodeImg');
                    // qrcodeImg.src = response.data.qrCodeUrl || './img/qrcode-demo.png';

                    // // 开始轮询支付状态
                    // pollPaymentStatus();
                    layui.use('layer', function () {
                        const layer = layui.layer;
                        layer.msg('支付成功', { icon: 1 });

                        // 跳转到订单详情页
                        setTimeout(() => {
                            window.location.href = `./order-detail.html?id=${orderId}`;
                        }, 1500);
                    });
                } else {
                    layer.msg('获取支付信息失败', { icon: 2 });
                }
            })
            .catch(error => {
                layer.close(loadingIndex);
                console.error("获取支付信息失败:", error);
                layer.msg('获取支付信息失败，请重试', { icon: 2 });
            });
    });
}

// 轮询支付状态
function pollPaymentStatus() {
    let pollCount = 0;
    const maxPollCount = 60; // 最多轮询60次，即10分钟

    const pollTimer = setInterval(() => {
        pollCount++;

        if (pollCount > maxPollCount) {
            clearInterval(pollTimer);
            return;
        }

        ApiService.order.getOrderDetail(orderId)
            .then(response => {
                if (response.data && response.data.status === 'PAID') {
                    // 支付成功
                    clearInterval(pollTimer);

                    layui.use('layer', function () {
                        const layer = layui.layer;
                        layer.msg('支付成功', { icon: 1 });

                        // 跳转到订单详情页
                        setTimeout(() => {
                            window.location.href = `./order-detail.html?id=${orderId}`;
                        }, 1500);
                    });
                }
            })
            .catch(error => {
                console.error("轮询支付状态失败:", error);
            });
    }, 10000); // 每10秒轮询一次

    // 将轮询定时器保存到window对象，以便在页面卸载时清除
    window.pollPaymentStatusTimer = pollTimer;
}

// 取消支付
function cancelPayment() {
    layui.use('layer', function () {
        const layer = layui.layer;

        layer.confirm('确定要取消支付吗？', { icon: 3, title: '提示' }, function (index) {
            // 跳转到订单详情页
            window.location.href = `./order-detail.html?id=${orderId}`;

            layer.close(index);
        });
    });
}

// 页面卸载时清除定时器
window.addEventListener('beforeunload', function () {
    if (countdownTimer) {
        clearInterval(countdownTimer);
    }

    if (window.pollPaymentStatusTimer) {
        clearInterval(window.pollPaymentStatusTimer);
    }
});

// 订单支付页面脚本
document.addEventListener('DOMContentLoaded', function () {
    // 检查登录状态
    if (!AuthService.isLoggedIn()) return;

    // 获取订单ID
    const urlParams = new URLSearchParams(window.location.search);
    const orderId = urlParams.get('orderId');

    if (!orderId) {
        layui.use('layer', function () {
            const layer = layui.layer;
            layer.msg('订单ID不能为空', { icon: 2 });
            setTimeout(() => {
                window.location.href = './order.html';
            }, 1500);
        });
        return;
    }

    // 加载订单信息
    loadOrderInfo(orderId);

    // 绑定支付方式选择事件
    // bindPaymentMethodEvents();

    // 绑定按钮事件
    // bindButtonEvents(orderId);
});

// 渲染订单商品
function renderOrderItems(items) {
    if (!items || items.length === 0) {
        document.querySelector('.order-items-list').innerHTML = `
            <div class="empty-items">
                <p>暂无商品信息</p>
            </div>
        `;
        return;
    }

    let itemsHtml = '';
    let totalQuantity = 0;
    let totalPrice = 0;

    items.forEach(item => {
        const book = item.book || {};
        const itemTotal = (item.price * item.quantity).toFixed(2);

        totalQuantity += item.quantity;
        totalPrice += parseFloat(itemTotal);

        itemsHtml += `
            <div class="order-item">
                <div class="item-image">
                    <img src="${book.imageUrl || './img/book-placeholder.jpg'}" alt="${book.title || '图书'}">
                </div>
                <div class="item-name">
                    <p>${book.title || '未知图书'}</p>
                    <p class="item-author">${book.author || ''}</p>
                </div>
                <div class="item-price">¥${item.price.toFixed(2)}</div>
                <div class="item-quantity">${item.quantity}</div>
                <div class="item-total">¥${itemTotal}</div>
            </div>
        `;
    });

    document.querySelector('.order-items-list').innerHTML = itemsHtml;
    document.getElementById('totalQuantity').textContent = totalQuantity;
    document.getElementById('totalPrice').textContent = `¥${totalPrice.toFixed(2)}`;
}

// 获取订单状态文本
function getOrderStatusText(status) {
    switch (status) {
        case '待付款': return '待付款';
        case '已付款': return '已付款';
        case '已发货': return '已发货';
        case '待发货': return '待发货';
        case '已完成': return '已完成';
        case '已取消': return '已取消';
        default: return '未知状态';
    }
}